#!/usr/bin/env node

const http = require('http'),
      https = require('https'),
      url = require('url'),
      fs = require('fs'),
      adr = 'https://maoyan.com/films?showType=3',
      cheerio = require('cheerio');

let movieList = [];

let opt = url.parse(adr);

opt.headers = {
  'user-agent':'curl/7.29.0'
};

https.get(opt,(res)=>{
  console.log(res.headers);
  let data = '';
  res.on('data',(chunck)=>data+=chunck);
  res.on('end',()=>{
    let $ = cheerio.load(data);
    let courses = $('body').find('div.movie-item-title');
    let coursesid = $('body').find('div.movie-item-title>a');
    let coursesif = $('body').find('div.channel-detail-orange');
    class myList{
      constructor(id,name,rang){
        this.movieId = id;
        this.movieName = name;
        this.movieRange = rang;
      }
    }

    for(let i=0;i<courses.length;i++){
      let name = $(courses[i]).attr('title');
      let id = $(coursesid[i]).attr('data-val');
      id = id.slice(9,id.length-1);
      let rang = $(coursesif[i]).text();

      movieList[i] = new myList(id,name,rang);
    }
  });
});

function genpage(){
  let html = fs.readFileSync('./index.html').toString('utf8');
  html = html.replace('/getdata','http://192.168.241.144:8080/getlist');
  return html;
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  let data = JSON.stringify(movieList);
  if(addr.pathname ==='/getlist'){
    res.writeHead(200,{
      'Content-Type':'application/json',
      'Content-length':Buffer.byteLength(data)
    }); 
    res.end(data);
  }
  else if(addr.pathname === '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-length':Buffer.byteLength(genpage())
    });
    res.end(genpage());
  }
  else if(addr.pathname !=='/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }
}).listen(8080);
